package com.googlecode.continuity.plugin.gwtext.client;

import java.util.HashMap;
import java.util.Map;

import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.EventListener;
import com.google.gwt.user.client.ui.FlexTable;

/**
 * FlexTableWithListeners
 * <p/>
 * Ok, this subclass and its listener propagation comes pretty close to a very dirty hack.
 * But to do this right, we'd have to change the GWT HTMLTable itself, the listener definition etc.... hm.
 *
 * @author Peter Schmitt <aragos@aragos.de>
 */
public class FlexTableWithListeners extends FlexTable {
  private Map rowListeners = new HashMap();
  private Map cellListeners = new HashMap();

  public FlexTableWithListeners() {
    sinkEvents(Event.MOUSEEVENTS);
  }

  public void setRowListener(Element row, EventListener listener) {
    // todo: init rowlisteners
    rowListeners.put(row, listener);
  }

  public void removeRowListener(Element row) {
    // todo: check rowlisteners
    rowListeners.remove(row);
  }

  public void setCellListener(Element td, EventListener listener) {
    // todo: init celllisteners
    cellListeners.put(td, listener);
  }

  public void removeCellListener(Element row) {
    // todo: check celllisteners
    cellListeners.remove(row);
  }

  /**
   * Method to process events generated from the browser.
   *
   * @param event the generated event
   */
  public void onBrowserEvent(Event event) {
    super.onBrowserEvent(event);
    if (rowListeners.size() == 0 && cellListeners.size() == 0) {
      return;
    }

    // Find out which cell and row are the target and propagate event to listener if available.
    Element td = getEventTargetCell(event);
    if (td == null) {
      return;
    }
    // TODO: check listener arrays
    if (cellListeners.containsKey(td)) {
      ((EventListener) cellListeners.get(td)).onBrowserEvent(event);
    }

    Element tr = DOM.getParent(td);
    /*
      you can get the row and column number like this:
      Element body = DOM.getParent(tr);
      int row = DOM.getChildIndex(body, tr);
      int column = DOM.getChildIndex(tr, td);
    */
    if (rowListeners.containsKey(tr)) {
      ((EventListener) rowListeners.get(tr)).onBrowserEvent(event);
    }
  }
}
